// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: "cloud1-8g31y2xod9947c95"
})

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database();
  const _ = db.command
  const $ = db.command.aggregate
  const myopenid = wxContext.OPENID

  console.log("execute " + event.function)
  if (event.function == "getActicleByid") {
    /**
     * 根据文字id获取文章信息
     *  params _id 文章的id
     */
    return await db.collection("publishInfo")
      .aggregate()
      .match({
        _id: event._id
      })
      .lookup({
        from: "users",
        localField: "_openid",
        foreignField: "_openid",
        as: "user"
      })
      .end()
  } else if (event.function == "getAllActicleList") {
    /**
     * 获取所有的文章 不分类别
     * params 
     *  skip: 跳过的数量
     *  limit： 取出的数量
     */
    let type = event.type;
    let where = {}
    if (type == 1) {
      where = {
        type: 1
      }
    } else if (type == 2) {
      where = {
        type: 2
      }
    } else if (type == 3) {
      where = {
        type: 3
      }
    }
    return await db.collection('publishInfo')
      .where({
        ...where
      })
      .orderBy("timestamp", "desc")
      .skip(event.skip)
      .limit(event.limit)
      .get()
  } else if (event.function == "getActicleList") {
    /**
     * 获取某人发表的文章
     */
    let openid = event.openid;
    if (!openid) {
      openid = myopenid
    }
    return await db.collection('publishInfo')
      .where({
        _openid: openid
      })
      .orderBy("timestamp", "desc")
      .skip(event.skip)
      .limit(event.limit)
      .get()
  } else if (event.function == "getSearchActicleList") {
    let keyWord = event.search;
    let k = ".*" + keyWord + ".*"

    return await db.collection('publishInfo')
      .where({
        text: db.RegExp({
          regexp: k,
          options: 'i',
        }),
      })
      .get()

  } else if (event.function == "isPraised") {
    /**
     * 判断是否已经点赞
     */
    let id = event.articleId;
    return await db.collection("praise")
      .where({
        acticleId: id,
        _openid: myopenid
      })
      .count()
  } else if (event.function == "praise") {
    /**
     * 点赞模块
     */
    try {
      let id = event.articleId;
      return await db.collection('praise').add({
        data: {
          _openid: myopenid,
          acticleId: id,
          isread: false,
          time: new Date(),
          timestamp: new Date().getTime()
        }
      })
    } catch (e) {
      console.log(e)
    }
  } else if (event.function == "getPraiseNum") {
    /**
     * 获取文章的点赞的数量
     */
    let id = event.articleId;
    return await db.collection("praise")
      .where({
        acticleId: id
      })
      .count()

  } else if (event.function == "getPraiseNumByOpenid") {
    /**
     * 获取此人的所有文章说获取的所有赞
     */
    let openid = event.otheropenid
    return await db.collection("praise")
      .aggregate()
      .lookup({
        from: "publishInfo",
        localField: "acticleId",
        foreignField: "_id",
        as: "acticle"
      })
      .match({
        "acticle._openid": openid,
      })
      .count("count")
      .end()
  } else if (event.function == "getUploadNumByOpenid") {
    /**
     * 获取用户发布的文章的数量
     */
    let _openid = event.otheropenid
    return await db.collection('publishInfo').aggregate()
      .match({
        _openid: _openid
      })
      .count("count")
      .end()
  } else if (event.function == "getComments") {
    /**
     * 获取评论内容
     */
    if (!event._id) {
      return false
    }
    return await db.collection("comments").aggregate()
      .match({
        articleId: event._id
      })
      .lookup({
        from: "users",
        localField: "_openid",
        foreignField: "_openid",
        as: "user"
      })
      .sort({
        timestamp: -1,
      })
      .skip(event.skip)
      .limit(event.limit)
      .end()
  } else if (event.function == "getCommentsNum") {
    /**
     * 获取此文章的评论数量
     */
    return await db.collection('comments').aggregate()
      .match({
        articleId: event._id
      })
      .count("count")
      .end()
  } else if (event.function == "getCommentInfoByOpenid") {
    /**
     * 获取此人的文章的评论信息
     */
    let match = {
      "acticle._openid": myopenid,
    }
    return await db.collection("comments")
      .aggregate()
      .lookup({
        from: "users",
        localField: "_openid",
        foreignField: "_openid",
        as: "user"
      })
      .lookup({
        from: "publishInfo",
        localField: "articleId",
        foreignField: "_id",
        as: "acticle"
      })
      .match({
        ...match
      })
      .sort({
        timestamp: -1
      })

      .skip(event.skip)
      .limit(event.limit)
      .end()
  } else if (event.function == "getPraiseInfoByOpenid") {
    /**
     * 获取此人的文章的点赞
     */
    let match = {
      "acticle._openid": myopenid,
    }
    if (event.isread) {
      match = {
        "acticle._openid": myopenid,
        isread: false
      }
    }
    return await db.collection("praise")
      .aggregate()
      .lookup({
        from: "users",
        localField: "_openid",
        foreignField: "_openid",
        as: "user"
      })
      .lookup({
        from: "publishInfo",
        localField: "acticleId",
        foreignField: "_id",
        as: "acticle"
      })
      .match({
        ...match
      })
      .sort({
        timestamp: -1
      })
      .skip(event.skip)
      .limit(event.limit)
      .end()
  } else if (event.function == "deleteAllCommentByActicleId") {
    /**
     * 删除文章的相关评论
     */
    try {
      return await db.collection("comments").where({
        articleId: event._id
      }).remove()
    } catch (e) {
      console.log(e)
    }
  } else if (event.function == "deleteAllPraiseByActicleId") {
    /**
     * 删除文章的相关点赞
     */
    try {
      return await db.collection("praise").where({
        acticleId: event._id
      }).remove()
    } catch (e) {
      console.log(e)
    }
  } else if (event.function == "getCommentNoReadNum") {
    /**
     * 获取未读的评论数量
     */
    return await db.collection("comments")
      .aggregate()
      .lookup({
        from: "publishInfo",
        localField: "articleId",
        foreignField: "_id",
        as: "acticle"
      })
      .match({
        "acticle._openid": myopenid,
        isread: false
      })
      .end()
  } else if (event.function == "getPraiseNoReadNum") {
    /**
     * 获取未读的点赞数量
     */
    return await db.collection("praise")
      .aggregate()
      .lookup({
        from: "publishInfo",
        localField: "acticleId",
        foreignField: "_id",
        as: "acticle"
      })
      .match({
        "acticle._openid": myopenid,
        isread: false
      })
      .end()
  } else if (event.function == "setIsread") {
    /**
     * 获取未读的消息标为已读
     */
    try{
      return await db.collection(event.collection).doc(event._id).update({
        data: {
          isread: true
        }
      })
    }catch(e){
      console.log(e)
    }
  }
}